package com.leo.client;

import com.leo.protocol.LoginRequestPacket;
import com.leo.protocol.LoginResponsePacket;
import com.leo.protocol.Packet;
import com.leo.protocol.PacketCodeC;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;
import java.util.UUID;

/**
 * @ClassName ClientHandler
 * @Description
 * @Author wangss
 * @date 2022.03.24 20:46
 * @Version 1.0
 */
public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(new Date() + ": 客户端开始登录");

        // 登录信息
        LoginRequestPacket packet = new LoginRequestPacket();
        packet.setUserId(UUID.randomUUID().toString());
        packet.setUsername("wangss");
        packet.setPassword("123");

        // 编码
        ByteBuf encode = PacketCodeC.INSTANCE.encode(ctx.alloc(), packet);

        // 发送信息
        ctx.channel().writeAndFlush(encode);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 收到的信息
        ByteBuf byteBuf = (ByteBuf) msg;

        // 解码
        Packet decode = PacketCodeC.INSTANCE.decode(byteBuf);

        // 如果是响应信息
        if (decode instanceof LoginResponsePacket) {
            LoginResponsePacket packet = (LoginResponsePacket) decode;
            if (packet.isSuccess()) {
                System.out.println(new Date() + ": 客户端登录成功");
            } else {
                System.out.println(new Date() + ": 客户端登录失败，原因：" + packet.getReason());
            }
        }
    }
}
